﻿using FlashPay.DAO.Interface;
using FlashPay.DAO.Shared;
using FlashPay.EF;
using FlashPay.EF.Models;
using FlashPay.Entity;
using FlashPay.Entity.DAORequest.Bank;
using FlashPay.Entity.Enum;
using FlashPay.Entity.Parameter;
using FlashPay.Entity.Response.BankCard;
using FlashPay.Entity.Response.Company;
using FlashPay.Entity.Response.Order;
using FlashPay.Util;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace FlashPay.DAO.Impl
{
    public class BankCardDaolmpl : BaseDAO, IDisposable, BankCardDao
    {
        #region 注入
        /// <summary>
        /// EF上下文
        /// </summary>
        private FlashPayContext dbContext { set; get; }

        /// <summary>
        /// 公司数据接口
        /// </summary>
        private readonly CompanyDao _companyDao;

        /// <summary>
        /// 注入
        /// </summary>
        /// <param name="context"></param>
        public BankCardDaolmpl(FlashPayContext context, CompanyDao companyDAO)
        {
            dbContext = context;
            _companyDao = companyDAO;
        }

        public void Dispose()
        {
            if (dbContext != null)
            {
                dbContext.Dispose();
            }
        }
        #endregion

        /// <summary>
        /// 获取所有銀行卡记录
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public List<BankCard> GetList(BankCardQuery query)
        {
            List<BankCard> result = new List<BankCard>();

            if (query != null)
            {
                //多条件查询
                var where = PredicateBuilder.True<BankCard>();
                //银行卡启用状态
                if (query.EnableStatus.HasValue)
                {
                    where = where.And(c => c.EnableStatus == query.EnableStatus.Value);
                }
                //订单号
                if (query.OrderNo != 0)
                {
                    where = where.And(c => c.OrderNo == query.OrderNo);
                }
                if (query.NoEqualBCId.HasValue)
                {
                    where = where.And(c => c.Bcid != query.NoEqualBCId.Value);
                }
                //銀行卡號
                if (!string.IsNullOrEmpty(query.CardNumber))
                {
                    where = where.And(c => c.CardNumber == query.CardNumber);
                }
                //銀行卡用戶名
                if (!string.IsNullOrEmpty(query.CardName))
                {
                    where = where.And(c => c.CardName == query.CardName);
                }
                var CList = dbContext.BankCard.Where(where.Compile()).ToList();
                result = CList;
            }
            return result;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="userInfo">新增对象</param>
        /// <returns></returns>
        public long Insert(BankCard model)
        {
            //将对象加入到数据上下文的LogRecord集合中
            dbContext.BankCard.Add(model);
            //调用数据上下文的保存方法，将对象存数数据库
            dbContext.SaveChanges();

            return model.Bcid;
        }

        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="model"></param>
        public bool Update(BankCard model)
        {
            dbContext.Entry<BankCard>(model);
            dbContext.SaveChanges();

            return true;
        }

        /// <summary>
        /// 根据编号获取公司
        /// </summary>
        /// <param name="id">编号</param>
        /// <returns>Company</returns>
        public List<CompanyResponse> GetCompany(int companyId)
        {
            var companyRequest = new EF.Models.Company()
            {
                CompanyId = companyId,
                CompanyPid = -1,
                CompanyStatus = 1
            };

            var companyList = new BaseModel<List<EF.Models.Company>>();

            _companyDao.Get(companyList, companyRequest, 2);
            var companyResponse = new List<CompanyResponse>();
            if (companyList.Success)
            {
                foreach (var item in companyList.Result)
                {
                    companyResponse.Add(new CompanyResponse()
                    {
                        CompanyID = item.CompanyId,
                        CompanyName = item.CompanyName,
                    });
                }
            }
            return companyResponse;
        }

        /// <summary>
        /// 库存卡查询
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<SpareBankCardResponse> GetSparePager(BankCardQuery query)
        {
            var q = from bc in dbContext.BankCard
                    join ui in dbContext.UserInfo on bc.CreateUid equals ui.UId
                    join or in dbContext.OrderRecord on bc.OrderNo equals or.OrderNo

                    select new SpareBankCardResponse {
                        CompanyId =  ui.UCompanyId,
                        ReceiptUID = or.ReceiptUid,
                        PayUID = or.PayUid,
                        Bcid = bc.Bcid,
                        OrderNo = bc.OrderNo.ToString(),
                        BankName = bc.BankName,
                        CardNumber = bc.CardNumber,
                        SecCardNumber = bc.SecCardNumber,
                        CardName = bc.CardName,
                        CardType = bc.CardType,
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        LoginName = bc.LoginName,
                        PasswordLogin = bc.PasswordLogin,
                        PasswordQuery = bc.PasswordQuery,
                        PasswordPay = bc.PasswordPay,
                        PasswordShield = bc.PasswordShield,
                        UsbType = bc.UsbType,
                        OriginalPassword = bc.OriginalPassword,
                        AccountBank = bc.AccountBank,
                        DocumentNumber = bc.DocumentNumber,
                        PhoneNumber = bc.PhoneNumber,
                        PaymentStart = bc.PaymentStart,
                        PaymentEnd = bc.PaymentEnd,
                        PayFeeRatio = (bc.PayFeeRatio * 100).ToString("#0.00"),
                        DepositFeeRatio = (bc.DepositFeeRatio * 100).ToString("#0.00"),
                        CrossBankPay = bc.CrossBankPay,
                        DepositType = bc.DepositType,
                        Remark = bc.Remark,
                        CreateUid = bc.CreateUid,
                        CreateName = ui.ULoginName,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    };
            //订单号
            if (query.OrderNo!=null && query.OrderNo>0)
            {
                q = q.Where(c => c.OrderNo.Contains(query.OrderNo.ToString()));
            }
            //银行名称
            if(!string.IsNullOrEmpty(query.BankName))
            {
                q = q.Where(c=>c.BankName.Contains(query.BankName));
            }
            //银行卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
            }
            //银行卡用户名
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.CardName.Contains(query.CardName));
            }
            //银行卡类型
            if (query.CardType.HasValue) {
                q = q.Where(c => c.CardType == query.CardType);
            }
            //银行卡启用状态
            if (query.EnableStatus.HasValue)
            {
                q = q.Where(c => c.EnableStatus == query.EnableStatus.Value);
            }
            //银行卡启用状态
            if (query.EnableStatusList!=null && query.EnableStatusList.Any())
            {
                q = q.Where(c => query.EnableStatusList.Contains(c.EnableStatus));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }
            if (query.UserPermission != null) {
                if (query.UserPermission.Contains("BankCardSpareUndoneOrder") && query.UserPermission.Contains("BankCardSpareCompletedOrder"))
                {
                    //全部未完成订单卡、全部已完成订单卡
                    var orderIds = dbContext.OrderRecord.Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
                else if (query.UserPermission.Contains("BankCardSpareUndoneOrder"))
                {
                    //全部未完成订单卡（√）
                    var orderIds = dbContext.OrderRecord.Where(p => p.DepositUid == 0 || p.ReceiptUid == 0 || p.PayUid == 0).Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
                else if (query.UserPermission.Contains("BankCardSpareCompletedOrder"))
                {
                    //全部已完成订单卡（√）
                    var orderIds = dbContext.OrderRecord.Where(p => p.DepositUid > 0 && p.ReceiptUid > 0 && p.PayUid > 0).Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
                else
                {
                    //默认
                    var orderIds = dbContext.OrderRecord.Where(p => p.DepositUid >0 && p.PayUid == 0 && p.CreateUid == query.CreateUid).Select(p => p.OrderNo).ToList();
                    q = q.Where(c => orderIds.Contains(long.Parse(c.OrderNo)));
                }
            }

            return new PagedList<SpareBankCardResponse>
            {
                TData = q.OrderByDescending(r => r.CreateDate).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList(),
                CurrentPageIndex = query.CurrentPageIndex.Value,
                TotalCount = q.Count(),
                Success = true
            };
        }

        /// <summary>
        /// 获取库存卡报表
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns>List<CardMerchant></returns>
        public List<BankCardExpResponse> GetPareListExp(BankCardQuery query)
        {
            var q = from bc in dbContext.BankCard
                    join ui in dbContext.UserInfo on bc.CreateUid equals ui.UId
                    //join or in dbContext.OrderRecord on bc.OrderNo equals or.OrderNo

                    select new BankCardExpResponse
                    {
                        CompanyId = ui.UCompanyId,
                        //ReceiptUID = or.ReceiptUid,   
                        订单号 = bc.OrderNo.ToString(),
                        银行名称 = bc.BankName,
                        银行卡用户名 = bc.CardName,
                        银行卡号 = bc.CardNumber,
                        银行副卡号 = bc.SecCardNumber,
                        银行卡类型 = bc.CardType.ToString(),
                        银行卡使用状态 = bc.UsingStatus,
                        银行卡启用状态 = bc.EnableStatus,
                        建立人员 = ui.ULoginName,
                        建立时间 = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                        备注 = bc.Remark,
                    };
            //订单号
            if (query.OrderNo != null && query.OrderNo > 0)
            {
                q = q.Where(c => c.订单号.Contains(query.OrderNo.ToString()));
            }
            //银行卡号
            if (!string.IsNullOrEmpty(query.CardNumber))
            {
                q = q.Where(c => c.银行卡号.Contains(query.CardNumber));
            }
            //银行卡用户名
            if (!string.IsNullOrEmpty(query.CardName))
            {
                q = q.Where(c => c.银行卡用户名.Contains(query.CardName));
            }
            //银行卡类型
            if (query.CardType.HasValue)
            {
                q = q.Where(c => c.银行卡类型 == query.CardType.ToString());
            }
            //银行卡启用状态
            if (query.EnableStatus.HasValue)
            {
                q = q.Where(c => c.银行卡启用状态 == query.EnableStatus.Value);
            }
            //银行卡启用状态
            if (query.EnableStatusList != null && query.EnableStatusList.Any())
            {
                q = q.Where(c => query.EnableStatusList.Contains(c.银行卡启用状态));
            }
            //公司
            if (query.CompanyIds != null && query.CompanyIds.Any())
            {
                q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
            }
            var CList = q.OrderByDescending(r => r.建立时间).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList();

            return CList;
        }


        /// <summary>
        /// 分頁查詢所有銀行卡
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public PagedList<BankCardResponse> GetPager(BankCardQuery query, bool isSpare = false)
        {
            var q = from bc in dbContext.BankCard
                    join ui in dbContext.UserInfo on bc.CreateUid equals ui.UId
                    //join c in dbContext.Company on bc.CompanyId equals c.CompanyId
                    select new BankCardResponse
                    {
                        CompanyNameId = bc.CompanyId,
                        CompanyId = ui.UCompanyId,
                        Bcid = bc.Bcid,
                        OrderNo = bc.OrderNo.ToString(),
                        BankName = bc.BankName,
                        CardNumber = bc.CardNumber,
                        SecCardNumber = bc.SecCardNumber,
                        CardName = bc.CardName,
                        CardType = bc.CardType,
                        UsingStatus = bc.UsingStatus,
                        EnableStatus = bc.EnableStatus,
                        LoginName = bc.LoginName,
                        PasswordLogin = bc.PasswordLogin,
                        PasswordQuery = bc.PasswordQuery,
                        PasswordPay = bc.PasswordPay,
                        PasswordShield = bc.PasswordShield,
                        UsbType = bc.UsbType,
                        OriginalPassword = bc.OriginalPassword,
                        AccountBank = bc.AccountBank,
                        DocumentNumber = bc.DocumentNumber,
                        PhoneNumber = bc.PhoneNumber,
                        PaymentStart = bc.PaymentStart,
                        PaymentEnd = bc.PaymentEnd,
                        PayFeeRatio = bc.PayFeeRatio,
                        DepositFeeRatio = bc.DepositFeeRatio,
                        CrossBankPay = bc.CrossBankPay,
                        DepositType = bc.DepositType,
                        Remark = bc.Remark,
                        CreateUid = bc.CreateUid,
                        CreateDate = bc.CreateDate.ToString("yyyy-MM-dd HH:mm:ss"),
                    };
            if (query != null)
            {
                //银行卡启用状态
                if (query.EnableStatus != 0 && query.EnableStatus != null)
                {
                    q = q.Where(c => c.EnableStatus == query.EnableStatus);
                }
                else
                {
                    q = q.Where(c => c.EnableStatus == 1|| c.EnableStatus == 2);
                }
                //订单号
                if(query.OrderNo!=0)
                {
                    q = q.Where(c => c.OrderNo== query.OrderNo.ToString());
                }
                //银行卡类型
                if (query.CardType != 0)
                {
                    q = q.Where(c => c.CardType == query.CardType);
                }
                if (query.CompanyIds != null && query.CompanyIds.Any())
                {
                    q = q.Where(c => query.CompanyIds.Contains(c.CompanyId));
                }
                //銀行卡號
                if (!string.IsNullOrEmpty(query.CardNumber))
                {
                    q = q.Where(c => c.CardNumber.Contains(query.CardNumber));
                }
                //銀行卡用戶名
                if (!string.IsNullOrEmpty(query.CardName))
                {
                    q = q.Where(c => c.CardName.Contains(query.CardName));
                }
                //状态
                if (query.Status.HasValue)
                {
                    if (query.Status.Value == 0)
                        q = q.Where(c => c.CompanyNameId == 0);
                    else
                        q = q.Where(c => c.CompanyNameId > 0);
                }
            }
            return new PagedList<BankCardResponse>
            {
                TData = q.OrderByDescending(r => r.CreateDate).Skip((query.CurrentPageIndex.Value - 1) * query.PageSize.Value).Take(query.PageSize.Value).ToList(),
                CurrentPageIndex = query.CurrentPageIndex.Value,
                TotalCount = q.Count(),
                Success = true
            };
        }

        /// <summary>
        /// 根据编号获取银行卡信息
        /// </summary>
        /// <param name="bcid">银行卡编号</param>
        /// <returns>CardMerchant</returns>
        public BankCard GetBankCardByBcid(int bcid)
        {
            BankCard result = new BankCard();
            //处理一种特殊情况
            if (bcid == -1)
            {
                int status = (int)BankCardEnableStatus.启用;
                result = dbContext.BankCard.Where(x => x.EnableStatus== status && x.UsingStatus== status).FirstOrDefault();
            }
            else
            {
                result=dbContext.BankCard.Where(x => x.Bcid == bcid).FirstOrDefault();
            }
            return result;
        }
        /// <summary>
        /// 根据银行卡号获取银行卡额外信息
        /// </summary>
        /// <param name="CardNumber"></param>
        /// <returns></returns>
        public List<BankCardExtraLimit> GetBankCardLimitByCardNumber(string CardNum)
        {
            List<BankCardExtraLimit> result = dbContext.BankCardExtraLimit.Where(x => x.CardNumber == CardNum).ToList();
            return result;
        }
        /// <summary>
        /// 根据银行卡号获取银行卡信息
        /// </summary>
        /// <param name="cardnumber">银行卡号</param>
        /// <returns>CardMerchant</returns>
        public bool GetBankCardByCardnumber(string Cardnumber)
        {

            bool result = false;
            BankCard bankCard = dbContext.BankCard.Where(x => x.CardNumber == Cardnumber).FirstOrDefault();
            if (bankCard != null )
            {
                result = true;
            }
            return result;
        }
        /// <summary>
        /// 根据银行卡号获取银行卡额外限制是否存在
        /// </summary>
        /// <param name="cardnumber">银行卡号</param>
        /// <returns>CardMerchant</returns>
        public bool GetBankCardLimitByCardnumber(string Cardnumber)
        {

            bool result = false;
            BankCardExtraLimit bankCardlimit = dbContext.BankCardExtraLimit.Where(x => x.CardNumber == Cardnumber).FirstOrDefault();
            if (bankCardlimit != null)
            {
                result = true;
            }
            return result;
        }

        /// <summary>
        /// 根据卡号或者用户名获取银行卡信息
        /// </summary>
        /// <param name="NumberOrName">银行卡号或者银行卡用户名</param>
        /// <param name="Strwhere">栏位</param>
        /// <returns></returns>
        public List<BankCard> GetBankCardByNumberOrName(string NumberOrName, string Strwhere)
        {
            List<BankCard> result = new List<BankCard>();
            if (Strwhere == "1")//银行卡号
            {
                result = dbContext.BankCard.Where(x => x.CardNumber.Contains(NumberOrName)).Take(10).ToList();
            }
            if (Strwhere == "2")//银行卡用户名
            {
                result = dbContext.BankCard.Where(x => x.CardName.Contains(NumberOrName)).Take(10).ToList();
            }
            return result;
        }

        /// <summary>
        /// 新增銀行卡信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool AddBankCard(BankCard model, bool isSpare = false)
        {
            bool result = false;
            if (dbContext.BankCard.Where(b => b.CardNumber == model.CardNumber).Count() == 0)//如果沒有該銀行卡信息則新增
            {
                model.PasswordLogin = EncryptHelper.enCryptDES(model.PasswordLogin);//登陆密码
                model.PasswordQuery = EncryptHelper.enCryptDES(model.PasswordQuery);//查询密码
                model.PasswordPay = EncryptHelper.enCryptDES(model.PasswordPay);//支款密码
                model.PasswordShield = EncryptHelper.enCryptDES(model.PasswordShield);//网盾密码
                model.OriginalPassword= EncryptHelper.enCryptDES(model.OriginalPassword);//原始密码
                dbContext.BankCard.Add(model);
                dbContext.SaveChanges();
                result = true;

            }
            else if (dbContext.BankCard.Where(b => b.CardNumber == model.CardNumber).Count() == 1)//如果存在該銀行卡信息
            {
                BankCard bc = dbContext.BankCard.Where(x => x.CardNumber == model.CardNumber).FirstOrDefault();
                if (bc.EnableStatus == 3)//銀行卡啟用狀態為刪除
                {
                    bc.BankCode = model.BankCode;
                    bc.CardName = model.CardName;
                    bc.CardNumber = model.CardNumber;
                    bc.CardType = model.CardType;
                    bc.CompanyId = model.CompanyId;
                    bc.CreateDate = model.CreateDate;
                    bc.CreateUid = model.CreateUid;
                    bc.CrossBankPay = model.CrossBankPay;
                    bc.DepositFeeRatio = model.DepositFeeRatio;
                    bc.DepositType = model.DepositType;
                    bc.DocumentNumber = model.DocumentNumber;
                    bc.EnableStatus = 1;//銀行卡狀態啟用
                    bc.LoginName = model.LoginName;
                    bc.OriginalPassword = model.OriginalPassword;
                    bc.PasswordLogin = model.PasswordLogin;
                    bc.PasswordPay = model.PasswordPay;
                    bc.PasswordQuery = model.PasswordQuery;
                    bc.PasswordShield = model.PasswordShield;
                    bc.PayFeeRatio = model.PayFeeRatio;
                    bc.PaymentStart = model.PaymentStart;
                    bc.PaymentEnd = model.PaymentEnd;
                    bc.PhoneNumber = model.PhoneNumber;
                    bc.Remark = model.Remark;
                    bc.UsbType = model.UsbType;
                    bc.UsingStatus = model.UsingStatus;
                    if (dbContext.SaveChanges() > 0)
                    {
                        result = true;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 修改銀行卡信息
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool UpdateBankCard(BankCard model, BankCardExtraLimit modelEx)
        {
            bool result = false;
            using (var tran = dbContext.Database.BeginTransaction())//打开事务
            {
            
            //BankCard bankCard = dbContext.BankCard.Find(model.Bcid);

            //bankCard.BankCode = model.BankCode;
            //bankCard.BankName = model.BankName;
            //bankCard.CardName = model.CardName;
            //bankCard.SecCardNumber = model.SecCardNumber;
            //bankCard.CardNumber = model.CardNumber;
            //bankCard.CardType = model.CardType;
            //bankCard.CompanyId = model.CompanyId;
            ////bankCard.CreateDate = model.CreateDate;
            ////bankCard.CreateUid = model.CreateUid;
            //bankCard.CrossBankPay = model.CrossBankPay;
            //bankCard.DepositFeeRatio = model.DepositFeeRatio;
            //if (model.CardType == 3)
            //    bankCard.DepositType = model.DepositType;//存款等级
            //else
            //    bankCard.DepositType = "";//存款等级

            //bankCard.DocumentNumber = model.DocumentNumber;
            //bankCard.EnableStatus = model.EnableStatus;//銀行卡狀態啟用
            //bankCard.LoginName = model.LoginName;

            //bankCard.OriginalPassword = EncryptHelper.enCryptDES(model.OriginalPassword);
            //bankCard.PasswordLogin = EncryptHelper.enCryptDES(model.PasswordLogin);
            //bankCard.PasswordPay = EncryptHelper.enCryptDES(model.PasswordPay);
            //bankCard.PasswordQuery = EncryptHelper.enCryptDES(model.PasswordQuery);
            //bankCard.PasswordShield = EncryptHelper.enCryptDES(model.PasswordShield);

            //bankCard.AccountBank = model.AccountBank;
            //bankCard.PayFeeRatio = model.PayFeeRatio;
            //bankCard.PaymentStart = model.PaymentStart;
            //bankCard.PaymentEnd = model.PaymentEnd;
            //bankCard.PhoneNumber = model.PhoneNumber;
            //bankCard.Remark = model.Remark;
            //bankCard.UsbType = model.UsbType;
            //bankCard.UsbSerialNumber = model.UsbSerialNumber;
            //bankCard.UsingStatus = model.UsingStatus;
            if (dbContext.SaveChanges() >= 0)
            {
                try
                {
                    #region 银行卡基本信息
                    BankCard bankCard = dbContext.BankCard.Find(model.Bcid);
                    bankCard.BankCode = model.BankCode;
                    bankCard.BankName = model.BankName;
                    bankCard.CardName = model.CardName;
                    bankCard.SecCardNumber = model.SecCardNumber;
                    bankCard.CardNumber = model.CardNumber;
                    bankCard.CardType = model.CardType;
                    bankCard.CompanyId = model.CompanyId;
                    bankCard.CrossBankPay = model.CrossBankPay;
                    bankCard.DepositFeeRatio = model.DepositFeeRatio;
                    if (model.CardType == 3)
                        bankCard.DepositType = model.DepositType;//存款等级
                    else
                        bankCard.DepositType = "";//存款等级
                    bankCard.DocumentNumber = model.DocumentNumber;
                    bankCard.EnableStatus = model.EnableStatus;//銀行卡狀態啟用
                    bankCard.LoginName = model.LoginName;
                    bankCard.OriginalPassword = EncryptHelper.enCryptDES(model.OriginalPassword);
                    bankCard.PasswordLogin = EncryptHelper.enCryptDES(model.PasswordLogin);
                    bankCard.PasswordPay = EncryptHelper.enCryptDES(model.PasswordPay);
                    bankCard.PasswordQuery = EncryptHelper.enCryptDES(model.PasswordQuery);
                    bankCard.PasswordShield = EncryptHelper.enCryptDES(model.PasswordShield);
                    bankCard.AccountBank = model.AccountBank;
                    bankCard.PayFeeRatio = model.PayFeeRatio;
                    bankCard.PaymentStart = model.PaymentStart;
                    bankCard.PaymentEnd = model.PaymentEnd;
                    bankCard.PhoneNumber = model.PhoneNumber;
                    bankCard.Remark = model.Remark;
                    bankCard.UsbType = model.UsbType;
                    bankCard.UsingStatus = model.UsingStatus;
                    #endregion
                    if (!GetBankCardLimitByCardnumber(modelEx.CardNumber))
                    {
                        dbContext.BankCardExtraLimit.Add(new BankCardExtraLimit
                        {
                            CardNumber = modelEx.CardNumber,
                            LimitChangetoDeposit = modelEx.LimitChangetoDeposit,
                            LimitDepositAmount = modelEx.LimitDepositAmount,
                            LimitChangetoPay = modelEx.LimitChangetoPay,
                            LimitPayAmount = modelEx.LimitPayAmount,
                            LimitOpenDate = modelEx.LimitOpenDate,
                            LimitCloseDate = modelEx.LimitCloseDate,
                            LimitRepeat = modelEx.LimitRepeat,
                            LimitStatus = modelEx.LimitStatus
                        });
                    }
                    else
                    {
                        BankCardExtraLimit bankCardExtraLimit = dbContext.BankCardExtraLimit.Find(modelEx.CardNumber);
                        bankCardExtraLimit.LimitChangetoDeposit = modelEx.LimitChangetoDeposit;
                        bankCardExtraLimit.LimitDepositAmount = modelEx.LimitDepositAmount;
                        bankCardExtraLimit.LimitChangetoPay = modelEx.LimitChangetoPay;
                        bankCardExtraLimit.LimitPayAmount = modelEx.LimitPayAmount;
                        bankCardExtraLimit.LimitOpenDate = modelEx.LimitOpenDate;
                        bankCardExtraLimit.LimitCloseDate = modelEx.LimitCloseDate;
                        bankCardExtraLimit.LimitRepeat = modelEx.LimitRepeat;
                        bankCardExtraLimit.LimitStatus = modelEx.LimitStatus;
                    }
                    if (dbContext.SaveChanges() >= 0)
                    {
                        result = true;
                        tran.Commit();
                    }
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    tran.Dispose();
                }
            }
            }
            return result;
        }

        /// <summary>
        /// 刪除銀行卡
        /// </summary>
        /// <param name="bcid"></param>
        /// <returns></returns>
        public bool DeleteBankCard(int Bcid, bool isSpare = false)
        {
            bool result = false;
            BankCard bankCard= dbContext.BankCard.Find(Bcid);
            if(isSpare)//库存卡
            {
                if (bankCard != null && bankCard.EnableStatus == 4 && bankCard.CompanyId == 0)//狀態必須為未授权状态,公司ID必須為0
                {
                    bankCard.EnableStatus = 3;//銀行卡狀態刪除;
                    if (dbContext.SaveChanges() > 0)
                    {
                        result = true;
                    }
                }
            }
            else
            {
                if (bankCard != null && bankCard.EnableStatus == 2 && bankCard.CompanyId == 0)//狀態必須為禁用狀態,公司ID必須為0
                {
                    bankCard.EnableStatus = 3;//銀行卡狀態刪除;
                    if (dbContext.SaveChanges() > 0)
                    {
                        result = true;
                    }
                }
            }
            return result;
        }

        /// <summary>
        /// 更改银行卡启用状态
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool ChangeBankCardSta(BankCard model)
        {
            bool result = false;
            BankCard bankCard = dbContext.BankCard.Find(model.Bcid);
            bankCard.EnableStatus = model.EnableStatus;
            if (dbContext.SaveChanges() > 0)
            {
                result = true;
            }
            return result;
        }

        #region 获取订单
        /// <summary>
        /// 查询(押金审核人>0 And 收货审核人=0 And 付款审核人=0 )
        /// </summary>
        /// <param name="query"></param>
        public List<AuditingOrderRecordResponse> GetAuditingOrderRecord(UserInfoQuery query)
        {
            var q = from cm in dbContext.OrderRecord
                    join ui in dbContext.UserInfo on cm.CreateUid equals ui.UId
                    where cm.DepositUid > 0 && cm.ReceiptUid == 0 && cm.PayUid == 0 && query.CompanyIds.Contains(ui.UCompanyId)
                    select new AuditingOrderRecordResponse
                    {
                        CompanyId = ui.UCompanyId,
                        OrderNo= cm.OrderNo.ToString(),
                        Cmid = cm.Cmid,
                        DeliveryNo = cm.DeliveryNo,
                        OrderDate = cm.OrderDate,
                        DepositAmount = cm.DepositAmount,
                        DepositDate = cm.DepositDate,
                        DepositUid = cm.DepositUid,
                        DepositCardNumber = cm.DepositCardNumber,
                        ReceiptDate = cm.ReceiptDate,
                        ReceiptUid = cm.ReceiptUid,
                        PayDate = cm.PayDate,
                        PayAmount = cm.PayAmount,
                        PayUid = cm.PayUid,
                        PayCardNumber = cm.PayCardNumber,
                        CreateUid = cm.CreateUid,
                        CreateDate = cm.CreateDate,
                    };


            return q.ToList();
        }
        #endregion

        public void Get(BaseModel<List<BankCard>> result, BankCardRequest model)
        {
            /* 呼叫資料庫 */
            IQueryable<BankCard> _result = dbContext.BankCard.Where(
                bankCard =>
                    (model.CompanyIds == null || model.CompanyIds.Contains(bankCard.CompanyId))
            );

            List<BankCard> list = Split(_result.OrderBy(bankCard => bankCard.Bcid), result.PageIndex, result.PageSize);
            Int32 totalCount = _result.Count();

            /* 結果複製 */
            result.Success = true;
            result.TotalCount = totalCount;
            result.Result = list;
        }
    }
}
